<?php

namespace Library;

use RuntimeException;
use ReflectionObject;

/**
 *
 */
class Fluent
{
    protected string $primaryKey = "id";

    /**
     * @return string
     */
    public function getPrimaryKey():string
    {
        return $this->primaryKey;
    }

    /**
     * @param $key
     * @param mixed|null $value
     * @return void
     */
    protected function set($key, mixed $value = null): void
    {
        if (property_exists($this,$key)) {
            $reflection = new ReflectionObject($this);
            try {
                $property = $reflection->getProperty($key);
                if ($property->isPublic()){
                    $this->{$key} = $value;
                }
            } catch (\ReflectionException $e) {
                throw new RuntimeException($e->getMessage());
            }
        }
    }

    /**
     * @param $key
     * @param mixed|null $default
     * @return mixed|null
     */
    protected function get($key, mixed $default = null): mixed
    {
        if (property_exists($this,$key)) {
            return $this->{$key};
        }
        return $default;
    }

    /**
     * @param $key
     * @return mixed|null
     */
    public function __get($key)
    {
        return $this->get($key);
    }

    /**
     * @param $key
     * @param mixed|null $value
     * @return void
     */
    public function __set($key, mixed $value = null)
    {
        $this->set($key, $value);
    }
}
